package com.ruoyi.safe.task;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.safe.constant.SafeJobConstants;
import com.ruoyi.safe.domain.CommonCooperator;
import com.ruoyi.safe.domain.CommonProject;
import com.ruoyi.safe.service.ICommonCooperatorService;
import com.ruoyi.safe.service.ICommonProjectService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
@AllArgsConstructor
public class EngineeringInfoSyncJob {

    private ICommonProjectService commonProjectService;

    private ICommonCooperatorService commonCooperatorService;

    private final String HOST = "http://192.168.1.118:8080";

    private final String PROJECT_SYNC_URL = HOST + "/show/XMJBXX/list";

    private final String COOPERATOR_SYNC_URL = HOST + "/show/LWFBSML/list";

    private final String TOKEN = "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjBmYjRmNDdiLWFlNDktNGQ1MS1hODgyLTU3MGU3YWE0ZWRhNiJ9.hzlGDFXwDjenhvBptE1SO1mHr6KI5sXwvdtHMbwwiMortiAHdBJcHqLPsNHMIatIEMeaZB_9-QTOO2FIg2vGfQ";

    @XxlJob(value = SafeJobConstants.ENGINEERING_INFO_SYNC)
    public ReturnT<String> executeJob() {
        try {
            // 同步项目信息
            projectSync();
            // 同步合作伙伴信息
            cooperatorSync();
        } catch (Exception e) {
            log.error("===== 调度发生的的异常为：{}", e.getMessage());
            return ReturnT.FAIL;
        }
        return ReturnT.SUCCESS;
    }

    private void cooperatorSync() {
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", TOKEN);
        String res = HttpUtils.doGet(COOPERATOR_SYNC_URL, null, header);
        log.info("cooperatorSync res : {}", res);
        TableDataInfo info = JSONObject.parseObject(res, TableDataInfo.class);
        if (info.getCode() == 200) {
            List<?> list = info.getRows();
            for (Object row : list) {
                JSONObject obj = JSONObject.from(row);
                if (obj.get("fId") == null || obj.get("fName") == null || obj.get("fShtyxydm") == null) {
                    log.warn("cooperatorSync param is null :{}", obj);
                    continue;
                }

                CommonCooperator dbData
                        = commonCooperatorService.selectCommonCooperatorByGapsCooperatorId(obj.getString("fId"));
                CommonCooperator commonCooperator = getCommonCooperator(obj);
                if (dbData == null) {
                    // 数据库没有这条记录，需要新增
                    log.info("cooperatorSync add : {}", JSON.toJSONString(commonCooperator));
                    commonCooperatorService.insertSyncCommonCooperator(commonCooperator);

                } else {
                    // 数据库中有这条记录，需要更新
                    log.info("cooperatorSync update : {}", JSON.toJSONString(commonCooperator));
                    commonCooperator.setId(dbData.getId());
                    commonCooperatorService.updateSyncCommonCooperator(commonCooperator);
                }
            }
        }
    }

    private CommonCooperator getCommonCooperator(JSONObject obj) {
        CommonCooperator commonCooperator = new CommonCooperator();
        commonCooperator.setEnterpriseName(obj.getString("fName"));
        commonCooperator.setCreditCode(obj.getString("fShtyxydm"));
        commonCooperator.setBadnessRecord(obj.getInteger("fBljl"));
        commonCooperator.setEnterpriseCode(obj.getString("fCode"));
        commonCooperator.setEnterpriseProperty(obj.getString("fDwxz"));
        commonCooperator.setSetUpDate(DateUtils.parseDate(obj.get("fRegisterdate")));
        if (obj.getString("fZczj") != null) {
            commonCooperator.setRegisterMoney(new BigDecimal(obj.getString("fZczj")));
        }
        commonCooperator.setEvaluateStatus(obj.getString("fPjzt"));
        commonCooperator.setAddress(obj.getString("fZcd"));
        commonCooperator.setBusinessScope(obj.getString("fJyfw"));
        commonCooperator.setDelFlag(obj.getString("fDeleted"));
        commonCooperator.setCreateBy(obj.getString("fCreatorName"));
        commonCooperator.setCreateTime(DateUtils.parseDate(obj.get("fCreateTime")));
        commonCooperator.setUpdateBy(obj.getString("fLastUpdateUserName"));
        commonCooperator.setUpdateTime(DateUtils.parseDate(obj.get("fLastUpdateTime")));
        commonCooperator.setGapsCooperatorId(obj.getString("fId"));
        // TODO 同步信息里面没有这个字段 暂定 其他
        commonCooperator.setEnterpriseType("16");
        // TODO 同步信息里面没有这个字段 暂定 N
        commonCooperator.setGovernmentAgency("N");
        return commonCooperator;
    }

    private void projectSync() {
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", TOKEN);
        String res = HttpUtils.doGet(PROJECT_SYNC_URL, null, header);
        log.info("projectSync res : {}", res);
        TableDataInfo info = JSONObject.parseObject(res, TableDataInfo.class);
        if (info.getCode() == 200) {
            List<?> list = info.getRows();
            for (Object row : list) {
                JSONObject obj = JSONObject.from(row);
                if (obj.get("fId") == null || obj.get("fName") == null) {
                    log.warn("projectSync param is null :{}", obj);
                    continue;
                }
                CommonProject dbData
                        = commonProjectService.selectCommonProjectByGapsProjectId(obj.getString("fId"));
                CommonProject commonProject = getCommonProject(obj);
                if (dbData == null) {
                    // 数据库没有这条记录，需要新增
                    log.info("projectSync add : {}", JSON.toJSONString(commonProject));
                    commonProjectService.insertSyncCommonProject(commonProject);
                } else {
                    // 数据库中有这条记录，需要更新
                    log.info("projectSync update : {}", JSON.toJSONString(commonProject));
                    commonProject.setId(dbData.getId());
                    commonProjectService.updateSyncCommonProject(commonProject);
                }
            }
        }
    }

    @NotNull
    private CommonProject getCommonProject(JSONObject obj) {
        CommonProject commonProject = new CommonProject();
        commonProject.setName(obj.getString("fName"));
        // TODO 是否是fCode
        commonProject.setCode(obj.getString("fFullCode"));
        commonProject.setAbbreviation(obj.getString("fXmjc"));
        commonProject.setSigningDept(obj.getLong("fDeptId"));
        commonProject.setProjectManager(obj.getString("fXmjl"));
        // commonProject.setPhone();
        // commonProject.setContractingModel();
        // commonProject.setProjectLevel("");
        commonProject.setParentCode(obj.getString("fPid"));
        // commonProject.setWhetherBloc();
        commonProject.setLicense(obj.getString("fSgxkzh"));
        // commonProject.setIndustryCategory();
        // commonProject.setProjectPrice();
        commonProject.setProjectStatus(getProjectStatus(obj.getString("fXmzt")));
        commonProject.setProjectAddress(obj.getString("fGcdd"));
        commonProject.setProjectOverview(obj.getString("fXmgk"));
        // commonProject.setSigningDate(DateUtils.parseDate(obj.get));
        commonProject.setStartDate(DateUtils.parseDate(obj.get("fHtkgrq")));
        commonProject.setEndDate(DateUtils.parseDate(obj.get("fHtjgrq")));
        commonProject.setDateCount(obj.getLong("fHtgqt"));

        commonProject.setRealStartDate(DateUtils.parseDate(obj.get("fSjkgrq")));
        commonProject.setRealEndDate(DateUtils.parseDate(obj.get("fSjwgrq")));
        commonProject.setRealDateCount(obj.getLong("fSjgqt"));

        // commonProject.setConstructionDept();
        commonProject.setBuildDept(obj.getString("fJsdw"));
        commonProject.setDesignDept(obj.getString("fSjdw"));
        commonProject.setSupervisionDept(obj.getString("fJldw"));
        commonProject.setOwnerDept(obj.getString("fDeptName"));
        // commonProject.setSurveyDept("");
        // commonProject.setOutsourcingDept();
        commonProject.setDelFlag(obj.getString("fDeleted"));
        commonProject.setCreateBy(obj.getString("fCreatorName"));
        commonProject.setCreateTime(DateUtils.parseDate(obj.get("fCreateTime")));
        commonProject.setUpdateBy(obj.getString("fLastUpdateUserName"));
        commonProject.setUpdateTime(DateUtils.parseDate(obj.get("fLastUpdateTime")));
        commonProject.setGapsProjectId(obj.getString("fId"));
        return commonProject;
    }

    private String getProjectStatus(String fXmzt) {
        if ("开工准备".equals(fXmzt)) {
            return "1";
        } else if ("在施".equals(fXmzt)) {
            return "2";
        } else if ("停工".equals(fXmzt)) {
            return "3";
        } else if ("完工".equals(fXmzt) || "竣工".equals(fXmzt)) {
            return "4";
        } else if ("保修".equals(fXmzt)) {
            return "8";
        } else if ("关闭".equals(fXmzt)) {
            return "9";
        }
        return null;
    }
}
